package service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class ZipCompressByFiles {
    static final int BUFFER = 8192;
    private File zipFile;

    public ZipCompressByFiles(String zipFileName) {
        //new a zip file
        zipFile = new File(zipFileName);
    }
    public void Compress(List<String> fileNameList) {
        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
            ZipOutputStream zos =new ZipOutputStream(cos);
            zos.setLevel(0);
            //in the zip , we set base dir is noting
            String basedir ="";
            for(String filePath:fileNameList) {
                CompressFile(new File(filePath), zos, basedir);
            }
            zos.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private void CompressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry ze = new ZipEntry(basedir + file.getName());
            out.putNextEntry(ze);
            int count;
            byte[] data = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, BUFFER);
            }
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String args[]) {
        ZipCompressByFiles zc = new ZipCompressByFiles("/home/luoqifei/ziplists/java.zip");
        List<String> list=new ArrayList<String>();
        list.add("/home/luoqifei/ziplists/1.txt");
        list.add("/home/luoqifei/ziplists/2.txt");
        list.add("/home/luoqifei/ziplists/3.loz");
        zc.Compress(list);
        System.out.println("OK/......");
    }
}